package io.github.bloquesoft.entity.storage.mybatisplus.springboot;

import io.github.bloquesoft.entity.storage.mybatisplus.ClassMapperBeanRegister;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.spring.mapper.MapperFactoryBean;

@Component
public class RegisterMapperBean implements BeanPostProcessor {

    @Autowired
    private final ClassMapperBeanRegister mapperRegister;

    public RegisterMapperBean(ClassMapperBeanRegister mapperRegister)
    {
        this.mapperRegister = mapperRegister;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        if (bean instanceof MapperFactoryBean)
        {
            try {
                Object mapperBean = ((MapperFactoryBean) bean).getObject();
                mapperRegister.register((Mapper<?>) mapperBean);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        if (Mapper.class.isAssignableFrom(bean.getClass())) {
            mapperRegister.register((Mapper<?>) bean);
        }
        return bean;
    }
}
